from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
from django.shortcuts import redirect
from . import models
import requests
from bs4 import BeautifulSoup
res=requests.get('http://news.qq.com/')
res.encodeing='utf-8';
soup=BeautifulSoup(res.text,features='html.parser');
tartet=soup.select("div.text > em.f14 > a.linkto")
# imglink=soup.select("div.pic > img.picto")
# 对返回的列表进行遍历

for n in tartet:
    obj = models.News()
    title = n.get_text()
    link = n.get("href")
    obj.titles=title
    obj.datads=link
    obj.save()
xxdd=models.News.objects.values('titles') 
print(xxdd)
# for i in imglink:
#     obj = models.News()
#     obj.imglinks=imglink.get("href")
#     obj.save()

# 删库操作 谨慎
# obj = models.News.objects
# obj.all().delete()
# Create your views here.

def login(request):
    return render(request,"login.html")

def register(request):
    article=models.Article.objects.get(pk=1)
    return render(request,"register.html",{'article':article})

def index(request):
    return render(request,'index.html')

def indexvt(request):
    return render(request,'index_v2.html')

def add(request):
    user = request.GET['user']
    password = request.GET['password']
    article=models.Article.objects.filter(user=user)
    x={}
    for i in article:
        x={'id':i.id,'user':i.user,'username':i.username} 
    if not user:
        return JsonResponse({'code':0,'msg':"用户名不能为空"})
    elif not password:
        return JsonResponse({'code':2,'msg':"密码不能为空"})
    elif not article:
        return JsonResponse({'code':1,'msg':"用户名不存在"})
    elif user == i.user and password != i.password:
        return JsonResponse({'code':3,'msg':"密码错误"})
    elif user == i.user and password == i.password:
        # return JsonResponse({'code':200,'msg':x})
        return JsonResponse({'code':200,'msg':'/yt/index/'})

def new(request):
    user = request.GET['user']
    password = request.GET['password']
    newuser = models.Article()
    newuser.user=user
    newuser.password=password
    newuser.save()
    if user:
        return JsonResponse({'code':200,'msg':"/yt/login"})